<template>
  <el-dialog
    :title="title"
    :visible.sync="addOrUpdateVisible"
    :before-close="cancel"
  >
    <el-form class="demo-ruleForm mt10 plr30" id="print-form">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="审批标题" prop="title">
            <el-input disabled v-model="obj.title"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="内容">
            <el-input
              type="textarea"
              disabled
              :autosize="{ minRows: 6, maxRows: 10 }"
              placeholder="请输入内容"
              v-model="obj.content"
              maxlength="255"
              show-word-limit
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-col :span="12" class="mt">
      <el-button type="primary" @click="details">审批内容</el-button>
    </el-col>
    <el-col :span="12" style="text-align: right">
      <el-button type="primary" @click="print">打印</el-button>
    </el-col>
    <el-table
      id="print-table"
      :data="tableData"
      :header-cell-style="{ 'text-align': 'center' }"
      :cell-style="{ 'text-align': 'center' }"
      border
      style="width: 100%; margin-top: 10px"
    >
      <el-table-column type="index" label="序号" width="50"> </el-table-column>
      <el-table-column prop="approvalDeptName" label="部门"> </el-table-column>
      <el-table-column prop="approvalStaffName" label="操作人">
      </el-table-column>
      <el-table-column prop="approvalIdea" label="审批意见"> </el-table-column>
      <el-table-column prop="signatureUrl" width="200px" label="附件">
        <template slot-scope="{ row }">
          <el-button
            size="mini"
            icon="el-icon-download"
            type="text"
            @click="handlePictureCardUpload(obj.title, row.signatureUrl)"
            v-if="row.signatureUrl"
            >下载
          </el-button>
          <div v-else>用户未上传附件</div>
        </template>
      </el-table-column>
      <el-table-column prop="approvalStatus" label="审批状态" width="100">
        <template slot-scope="{ row }">
          {{ filterExamineAndApprove(row.approvalStatus / 1) }}
        </template>
      </el-table-column>
    </el-table>
    <addDialog ref="addDialog" @dialogBack="(e) => a1" />
    <!-- <addDialog1 ref="addDialog1" @dialogBack="(e) => a1" /> -->
    <div id="print-area" style="display: none">
      <div class="demo-ruleForm mt10 plr30">
        <div class="row" style="margin: 10px">
          <div>审批标题: {{ obj.title }}</div>
          <div>内容: {{ obj.content }}</div>
        </div>
        <table style="margin-top: 10px" class="print-table">
          <thead>
            <tr>
              <th>序号</th>
              <th>部门</th>
              <th>操作人</th>
              <th>审批意见</th>
              <th>附件</th>
              <th>审批状态</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in tableData" :key="index">
              <td>{{ index + 1 }}</td>
              <td>{{ item.approvalDeptName }}</td>
              <td>{{ item.approvalStaffName }}</td>
              <td>{{ item.approvalIdea }}</td>
              <td>
                <span v-if="item.signatureUrl">已上传</span>
                <span v-else>用户未上传附件</span>
              </td>
              <td>{{ filterExamineAndApprove(item.approvalStatus / 1) }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import {
  approvalFromQueryByRecords, //获取审批记录
  approvalFromQueryFromById, //获取审批单详情
} from "@/api/system/Approval";
// import { checkoutInfo, installId } from "@/api/IMS/purchase";
import addDialog from "@/views/file/fileVersion/components/addDialog.vue";
// import addDialog from "@/views/IMS/purchase/components/addDialog.vue"; //采购详情
// import addDialog1 from "@/views/specSheet/components/addDialog.vue"; //我是审批
export default {
  components: {
    addDialog,
  },
  data() {
    return {
      title: "操作记录",
      addOrUpdateVisible: false,
      tableData: [],
      tableData1: [],
      obj: {},
      ExamineAndApprove: [
        { label: "未开始", value: 101 },
        { label: "已读", value: 102 },
        { label: "审批中", value: 201 },
        { label: "审核通过", value: 301 },
        { label: "驳回", value: 302 },
      ],
      tabH: "1",
      row: "",
      obj1: {},
      obj2: {},
    };
  },
  mounted() {
    this.$nextTick(function () {
      this.getHeight();
    });
    //改变高度 掉方法
    window.addEventListener("resize", this.getHeight);
  },
  methods: {
    filterExamineAndApprove(value) {
      // 查找匹配的项
      const result = this.ExamineAndApprove.find(
        (item) => item.value === value
      );
      // 如果找到，返回 label，否则返回 "未知状态"
      return result ? result.label : "未知状态";
    },
    print() {
      const printArea = document.getElementById("print-area");
      const printContent = printArea.innerHTML;
       
     // 保存原始内容
     const originalContent = document.body.innerHTML;
      const printWindow = window.open("", "", "height=500, width=800");
      printWindow.document.write("<html><head><title>打印</title>");
      printWindow.document.write("<style>");
      printWindow.document.write("@page { size: auto; margin: 0; }");
      printWindow.document.write("body { margin: 1.6cm; }");
      printWindow.document.write(
        ".print-table { width: 100%; text-align: center; border-collapse: collapse; }"
      );
      printWindow.document.write(
        ".print-table th, .print-table td { border: 1px solid black; padding: 8px; }"
      );
      printWindow.document.write("</style>");
      printWindow.document.write("</head><body>");
      printWindow.document.write(printContent);
      printWindow.document.write("</body></html>");
      printWindow.document.close();
      // 等待弹出窗口加载完成后再调用打印
      printWindow.onload = function () {
        printWindow.print();
      };

      // 打印完成后恢复原始内容并刷新页面
      printWindow.onafterprint = function () {
        printWindow.close();
        document.body.innerHTML = originalContent;
        window.location.reload();
      };
    },
    a1() {
      console.log("我是关闭调用");
    },
    // 下载图片
    async a(url1) {
      let num = 0;
      let url2 = url1;
      for (let i = 0; i < url1.length; i++) {
        if (url1[i] == ".") {
          num = i;
        }
      }
      let text = url2.substring(num);
      // let text1 = text.slice(1)
      // 获取图片对象和画布对象
      const imgUrl = url1;
      const response = await fetch(imgUrl);
      const blob = await response.blob();
      // 创建下载链接
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = `文档${text}`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      // 释放 Blob URL
      window.URL.revokeObjectURL(url);
    },
    handlePictureCardUpload(scope, url) {
  fetch(url)
    .then((response) => response.blob())
    .then((blob) => {
      // 创建一个隐藏的链接
      const link = document.createElement("a");
      link.style.display = "none";
      document.body.appendChild(link);

      // 创建一个URL对象
      const objectUrl = URL.createObjectURL(blob);
      link.href = objectUrl;

      // 提取文件名
      const filename = extractFilenameFromUrl(url);
      link.download = filename || "downloaded_file"; // 使用提取的文件名，如果没有则使用默认文件名

      // 模拟点击链接来下载文件
      link.click();

      // 清理资源
      URL.revokeObjectURL(objectUrl);
      document.body.removeChild(link);
    })
    .catch((error) => console.error("Download failed", error));

  // 提取文件名的函数
  function extractFilenameFromUrl(url) {
    const path = new URL(url).pathname; // 获取路径部分
    const filename = path.substring(path.lastIndexOf("/") + 1); // 提取最后一个斜杠后的内容
    return filename;
  }
},
    getHeight() {
      this.tabH = window.innerHeight - 500;
    },
    // 获取审批内容
    async details() {
      const type = Number(this.obj1.type);
      const businessId = this.obj1.businessId;
      let url = "";

      if (type === 1) {
        this.$refs.addDialog.visible(businessId);
      }
    },
    async init(id, row, type = 0, obj = {}, list) {
      try {
        type == 0 ? (this.title = "操作记录") : (this.title = "重新发起");
        this.obj2 = obj;
        this.row = row;
        if (id) {
          let res1 = "";
          row.hasOwnProperty("fromId")
            ? (res1 = await approvalFromQueryFromById({
                id: row.fromId,
              }))
            : (res1 = await approvalFromQueryFromById({ id: row.id }));
          this.obj = res1.data;
          this.obj1 = JSON.parse(JSON.stringify(res1.data));
          let res = await approvalFromQueryByRecords({ id: id });
          if (res.data.length) this.obj = res.data[0];
          this.tableData = res.data;
          this.tableData1 = list;
        }
      } catch (err) {
        console.log(err);
      }
      this.addOrUpdateVisible = true;
    },
    cancel() {
      this.$emit("dialogBack", false);
      this.addOrUpdateVisible = false;
    },
  },
};
</script>

<style scoped lang="less">
/deep/ .el-dialog__header {
  border-bottom: 1px solid #e9e9e9;
}

/deep/ .el-form--label-top .el-form-item__label {
  padding: 0 0;
}
.image-slot {
  line-height: 80px;
}
.mt {
  margin-bottom: 20px;
}
</style>
